package com.qqserver.service;

import com.qqcommon.Message;
import com.qqcommon.MessageType;
import com.qqcommon.User;
import com.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 向所有注册用户推送消息
 */
public class SendNewsToAll implements Runnable{
    private Scanner scanner = new Scanner(System.in);
    @Override
    public void run(){

        while(true){
            String s = null;
            System.out.print("输入向用户推送的消息（exit:退出）：");
            s = scanner.next();
            if (s.equals("exit")){
                break;
            }
            if (s != null){
                //创建消息对象
                Message message = new Message();
                message.setSender("Server");
                message.setSendTime(new Date().toString());
                message.setContent(s);
                message.setMesType(MessageType.MESSAGE_TO_ALL_MES);
                //获取注册用户
                HashMap<String, User> validUsers = UserStore.getValidUsers();
                //获取在线用户和对应线程
                HashMap<String,ServerConnectClientThread> hashMap = ManageServerConnectClientThread.getHm();
                //遍历用户发送消息
                Iterator<String> iterator = validUsers.keySet().iterator();//所有用户
                while (iterator.hasNext()){//所有用户
                    String user = iterator.next();
                    message.setGetter(user);//编写消息对象的接收者
                    for (String onlineUser:hashMap.keySet()){//在线用户
                        //在线情况下
                        if (onlineUser.equals(user)){
                            try {
                                ObjectOutputStream oos = new ObjectOutputStream
                                        (hashMap.get(onlineUser).getSocket().getOutputStream());
                                oos.writeObject(message);
                                oos.close();
                                System.out.println("发送成功");
                                break;//找到就终止
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //用户不在线情况下，离线
                    //将消息对象储存到StoreMessage
                    StoreMessage.addMessage(user,message);
                    System.out.println("用户不在线，消息暂存");
                }

            }
        }
    }
}
